package com.xszx.servlet;

import com.mysql.jdbc.AbandonedConnectionCleanupThread;
import com.xszx.beans.User;
import com.xszx.dao.UserDao;
import com.xszx.dao.impl.UserDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    static UserDao userDao = new UserDaoImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //修改编码
        req.setCharacterEncoding("utf-8");

        //接收前端参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = userDao.login(username, password);

        if (user == null) {
            req.setAttribute("msg", "用户名或密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        } else {
            req.getSession().setAttribute("username", username);
            if (user.getRank() == 0) {
                resp.sendRedirect("GetGoodsServlet");
            }else {
                resp.sendRedirect("IndexServlet");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
